from typing import List, Optional
from sqlalchemy.orm import Session
from datetime import datetime, date
from ..models.project import Project as ProjectModel, ProjectStatus
from ..models.task import Task
from ..schemas.project import ProjectCreate, ProjectUpdate
from fastapi import HTTPException, status

class ProjectService:
    def __init__(self, db: Session):
        self.db = db

    def get_projects(self, skip: int = 0, limit: int = 100) -> List[ProjectModel]:
        """获取项目列表"""
        return self.db.query(ProjectModel).offset(skip).limit(limit).all()

    def get_project(self, project_id: int) -> Optional[ProjectModel]:
        """根据ID获取项目"""
        return self.db.query(ProjectModel).filter(ProjectModel.id == project_id).first()

    def create_project(self, project_data: ProjectCreate, created_by: int) -> ProjectModel:
        """创建项目"""
        # 检查日期逻辑
        if project_data.end_date and project_data.end_date < project_data.start_date:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="结束日期不能早于开始日期"
            )
        
        # 创建新项目
        db_project = ProjectModel(**project_data.dict(), created_by=created_by)
        self.db.add(db_project)
        self.db.commit()
        self.db.refresh(db_project)
        return db_project

    def update_project(self, project_id: int, project_data: ProjectUpdate) -> ProjectModel:
        """更新项目信息"""
        db_project = self.get_project(project_id)
        if not db_project:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="项目不存在"
            )
        
        # 检查日期逻辑
        if project_data.end_date and project_data.start_date:
            if project_data.end_date < project_data.start_date:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="结束日期不能早于开始日期"
                )
        elif project_data.end_date:
            if project_data.end_date < db_project.start_date:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="结束日期不能早于开始日期"
                )
        elif project_data.start_date:
            if db_project.end_date and project_data.start_date > db_project.end_date:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="开始日期不能晚于结束日期"
                )
        
        # 更新项目状态时的逻辑检查
        if project_data.status == ProjectStatus.COMPLETED and db_project.status != ProjectStatus.COMPLETED:
            # 检查是否有未完成的任务
            has_uncompleted_tasks = self.db.query(Task).filter(
                Task.project_id == project_id,
                Task.status != "completed"
            ).first() is not None
            
            if has_uncompleted_tasks:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="项目还有未完成的任务，无法标记为已完成"
                )
        
        # 更新项目信息
        for key, value in project_data.dict(exclude_unset=True).items():
            setattr(db_project, key, value)
        
        self.db.commit()
        self.db.refresh(db_project)
        return db_project

    def delete_project(self, project_id: int) -> None:
        """删除项目"""
        db_project = self.get_project(project_id)
        if not db_project:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="项目不存在"
            )
        
        # 检查项目下是否有任务
        has_tasks = self.db.query(Task).filter(Task.project_id == project_id).first() is not None
        if has_tasks:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="项目下有任务，无法删除"
            )
        
        self.db.delete(db_project)
        self.db.commit()

    def get_project_by_status(self, status: ProjectStatus) -> List[ProjectModel]:
        """根据状态获取项目列表"""
        return self.db.query(ProjectModel).filter(ProjectModel.status == status).all()

    def get_project_stats(self, project_id: int) -> dict:
        """获取项目统计信息"""
        db_project = self.get_project(project_id)
        if not db_project:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="项目不存在"
            )
        
        # 获取项目下的任务总数
        total_tasks = self.db.query(Task).filter(Task.project_id == project_id).count()
        
        # 获取已完成的任务数
        completed_tasks = self.db.query(Task).filter(
            Task.project_id == project_id,
            Task.status == "completed"
        ).count()
        
        # 计算完成率
        completion_rate = (completed_tasks / total_tasks * 100) if total_tasks > 0 else 0
        
        # 检查项目是否逾期
        is_overdue = False
        if db_project.end_date and db_project.status != ProjectStatus.COMPLETED:
            is_overdue = date.today() > db_project.end_date
        
        return {
            "project_id": project_id,
            "project_name": db_project.name,
            "total_tasks": total_tasks,
            "completed_tasks": completed_tasks,
            "completion_rate": round(completion_rate, 2),
            "is_overdue": is_overdue,
            "status": db_project.status.value
        }